<?php

namespace app\admin\controller;

use app\admin\model\Role;
use think\facade\View;
use app\admin\service\RoleService;
use think\exception\ValidateException;

class RoleController extends BaseController
{
    public function index()
    {   
        $roleService = new RoleService();
        $list = $roleService->getRoleList();


        View::assign('list',$list);
        return View::fetch();
    }

    public function create()
    {
        return View::fetch();   
    }


    public function edit()
    {   
        $id = $this->request->get('id/d',);
        $roleService = new RoleService();

        $row = $roleService->findRoleDetail($id);
        
        View::assign('row',$row);
        return View::fetch();   
    }

    public function save()
    {   
        $param = $this->request->post();
        try {
            validate('RoleValidate')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }
        
        Role::create($param);

        return json(['code' => 1, 'msg' => '保存成功!']);
    }

    public function permission()
    {
        $role_id = $this->request->get('role_id/d');
        $roleService = new RoleService();
        $data = $roleService->getMenuTree($role_id);
        
        return View::fetch('',['role_id' => $role_id,'data' => json_encode($data['data']),'idArr' => json_encode($data['idArr'])]);
    }

    public function allow()
    {
        $param = $this->request->post();

        try{
            validate('RoleValidate.allow')->check($param);

        } catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        $roleService = new RoleService();
        $res = $roleService->savePermission($param['role_id'],$param['menus']);
       
        return $res ?  json(['code' => 1, 'msg' => '授权成功!']) : json(['code' => 0, 'msg' => '授权失败!']);
    }


    public function switch()
    {
        $param = $this->request->post();

        try {
            validate('RoleValidate.switch')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        Role::update($param);

        return json(['code' => 1, 'msg' => '更新成功!']);
    }

    public function update()
    {
        $param = $this->request->post();

        try {
            validate('RoleValidate.edit')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        Role::update($param);
       
        return json(['code' => 1, 'msg' => '更新成功!']);
    }


    public function delete()
    {
        $id = $this->request->get('id/d');
        $result = Role::destroy($id);

        return $result ?  json(['code' => 1, 'msg' => '删除成功!']) : json(['code' => 0, 'msg' => '删除失败!']);
    }
}